import {useUserStore} from "@/store/user";
import {storeToRefs} from "pinia";

type HttpMethod = "OPTIONS" | "GET" | "HEAD" | "POST" | "PUT" | "DELETE" | "TRACE" | "CONNECT"

export interface RequestSuccessCallbackResult<T> {
    data: T
    statusCode: number
    header: any
    cookies: string[]
}

export interface RequestFailedCallbackResult<T> extends UniNamespace.GeneralCallbackResult {
    data: T
    statusCode: number
}

export async function request<T>({url, method, data, header, isAuthenticated}: {
    url: string,
    method: HttpMethod,
    data?: any,
    header?: object,
    isAuthenticated?: boolean
}): Promise<RequestSuccessCallbackResult<T>> {
    const userStore = useUserStore()
    const {token} = storeToRefs(userStore)
    return new Promise((resolve, reject) => {
        uni.request({
            url: `http://43.138.245.109:8891${url}`,
            method: method,
            data: data,
            header: {
                Authorization: isAuthenticated ? `Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6Imp3dCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwicGFzc3dvcmQiOiIxMjM0NTYiLCJleHAiOjE3NDczNzU5NzF9.5xFZC-bUDWbeHbhxUsEFN8xy32APx8OmWihmDWA2edw` : undefined,
                ...header
            },
            success(result) {
                resolve({
                    data: result.data as T,
                    statusCode: result.statusCode,
                    header: result.header,
                    cookies: result.cookies
                })
            },
            async fail(error) {
                const result = error as RequestFailedCallbackResult<T>
                if (result.statusCode !== undefined && result.statusCode == 401) {
                    userStore.logout()
                    await uni.reLaunch({url: "/pages/index/index"})
                }
                reject(error)
            },
        })
    })
}
